package thread.communication;
import static java.lang.System.out;

/**
 * 
 * @author Shahid
 */
public class Polling implements Runnable {
	static int[] array = new int[30];
	/*
	 * Declare Volatile variable
	 * You mark the variable holding shared data as volatile
	 *  because you want changes made by one thread to be visible in another
	 */
	/*
	 * If you do not mark the variable as Volatile
	 * then the change to variable by the other thread may or may not be "visible" to the main thread.
	 * Try this and your do while loop won't execute
	 * 
	 */
	volatile static boolean isFilled = false;

	public void run() {
		
		try {
			for (int j = 0; j < 30; j++) {
				array[j] = j;
				Thread.sleep(1);
			}
		} catch (InterruptedException e) {
			out.println(e.toString());
		}
		
		isFilled = true; // Set the flag, when Job is completed.
	}

	public static void main(String[] args) throws Exception {
		
		new Thread(new Polling()).start();
		
		out.println("Print array values without Polling");
		print();
		
		out.println("\nPolling...");
		/*
		 * Polling a variable is a Performance hit, We should use Callback
		 */
		/*
		 *  How ever Loop can be executed without Volatile variable
		 *  if we add System.out.println() or Thread.sleep() statement
		 *  in the loop body which is a BAD choice
		 */
		do{
			// Waiting for Array to be filled
		}while(!isFilled);
		
		print();
	}

	static void print() {
		for (int i : array) {
			System.out.print(i + ",");
		}
		System.out.print("\n");
	}
}

// Output
// Print array values without Polling
// 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

// Polling...
// 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,

